#!/usr/bin/env python

import os
import re
import gtk
import tempfile
import subprocess

from subprocess import Popen

def render(text):
	file, path = tempfile.mkstemp('.tex', 'dummychat_tex')

	os.write(file, r'\documentclass{article}\usepackage{amsmath}\pagestyle{empty}\begin{document}' + text + '\end{document}')
	os.close(file)
	
	latex = Popen(["latex", '-interaction=nonstopmode', path], stdout = subprocess.PIPE, cwd = '/tmp')
	out, err = latex.communicate()
	print out
	latex.wait()
	
	dvips = Popen(["dvips", "-E -q", path[0:-4] + ".dvi"], cwd = '/tmp')
	dvips.wait()
	
	convert = Popen(["convert", "-density", "96", "-transparent", "white", path[0:-4] + ".ps", path[0:-4] + ".png"], cwd = '/tmp')
	convert.wait()
	
	return path[0:-4] + ".png"

def parse(data, tb):
	p = re.compile('<tex>(.+?)</tex>')
	slices = p.split(data)
	
	is_img = False
	for slice in slices:
		if is_img:
			img = gtk.gdk.pixbuf_new_from_file(render(slice))
			tb.insert_pixbuf(tb.get_end_iter(), img)
		else:
			tb.place_cursor(tb.get_end_iter())
			tb.insert_at_cursor(slice)
		is_img = not is_img

if __name__ == "__main__":
	render(r'$E=mc^2$')
